﻿create PROCEDURE Sync.SP_LoanFeasabilityStudyAttachments_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanFeasabilityStudyAttachments_Temp TABLE 
		(
			LoanFeasabilityStudyAttachmentID UniqueIdentifier,
			[LoanFeasabilityStudyID] uniqueidentifier,
				[Attachment] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanFeasabilityStudyAttachments_Temp 
	   SELECT	Tbl.Col.value('LoanFeasabilityStudyAttachmentID[1]','uniqueidentifier') LoanFeasabilityStudyAttachmentID,
                Tbl.Col.value('LoanFeasabilityStudyID[1]', 'uniqueidentifier') [LoanFeasabilityStudyID],
Tbl.Col.value('Attachment[1]', 'uniqueidentifier') [Attachment],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanFeasabilityStudyAttachments') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanFeasabilityStudyAttachments] ([LoanFeasabilityStudyAttachmentID],[LoanFeasabilityStudyID],[Attachment])
	SELECT t.[LoanFeasabilityStudyAttachmentID],t.[LoanFeasabilityStudyID],t.[Attachment]
	FROM  @LoanFeasabilityStudyAttachments_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanFeasabilityStudyAttachments_Tracking s
        WHERE t.LoanFeasabilityStudyAttachmentID = s.LoanFeasabilityStudyAttachmentID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanFeasabilityStudyAttachments]
	SET [LoanFeasabilityStudyAttachments].[LoanFeasabilityStudyID] = t.[LoanFeasabilityStudyID],[LoanFeasabilityStudyAttachments].[Attachment] = t.[Attachment] 
	FROM [dbo].[LoanFeasabilityStudyAttachments] s JOIN @LoanFeasabilityStudyAttachments_Temp t 
    ON t.LoanFeasabilityStudyAttachmentID = s.LoanFeasabilityStudyAttachmentID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanFeasabilityStudyAttachments_Tracking r
				  WHERE t.LoanFeasabilityStudyAttachmentID = r.LoanFeasabilityStudyAttachmentID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanFeasabilityStudyAttachments]
    FROM @LoanFeasabilityStudyAttachments_Temp t JOIN [dbo].[LoanFeasabilityStudyAttachments] s
    ON t.LoanFeasabilityStudyAttachmentID = s.LoanFeasabilityStudyAttachmentID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














